package com.axjy.web;

import com.axjy.pojo.User;
import com.axjy.service.UserService;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * Created by asus on 2018/1/10.
 */
@Controller
@RequestMapping("/user")
public class UploadCardHandler {
    @Resource
    private UserService userService;
    @PostMapping("/uploadCard")
    public String uploadCard(String cardDesc, MultipartFile cardImg, HttpSession session){
        String newFileName=UUID.randomUUID().toString().replace("-","");
        String suffix= FilenameUtils.getExtension(cardImg.getOriginalFilename());
        ServletContext sc=session.getServletContext();
        String realPath=sc.getRealPath("/static/attach");
        File folder=new File(realPath);
        if(folder.exists()==false){
            folder.mkdirs();
        };
        File newFile=new File(folder,newFileName+"."+suffix);
        try {
            cardImg.transferTo(newFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        User loginUser= (User) session.getAttribute("loginUser");
        userService.updateCard(loginUser.getId(),newFile.getName(),cardDesc);
        return "redirect:/user/list";
    }

}
